package com.leyou.sms.mq;

import com.leyou.common.constants.MQConstants;
import com.leyou.common.utils.RegexUtils;
import com.leyou.sms.config.SmsProperties;
import com.leyou.sms.utils.SmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class MessageListener {

    @Autowired
    private SmsUtils smsUtils;

    @Autowired
    private SmsProperties prop;

    /**
     * 监听注册验证码的短信
     *
     * @param msg 里面只包含2个参数：phone，手机号码； code：验证码
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstants.Queue.SMS_VERIFY_CODE_QUEUE, durable = "true"),
            exchange = @Exchange(name = MQConstants.Exchange.SMS_EXCHANGE_NAME, type = ExchangeTypes.TOPIC),
            key = MQConstants.RoutingKey.VERIFY_CODE_KEY
    ))
    public void listenVerifyCodeMessage(Map<String, String> msg) {
        // 取出手机号
        String phone = msg.get("phone");
        if(!RegexUtils.isPhone(phone)){
            // 手机号格式不正确
            log.error("手机号格式不正确！");
            return;
        }
        // 取出code
        String code = msg.get("code");
        if(!RegexUtils.isValidCode(code)){
            // 验证码格式不正确
            log.error("验证码格式不正确！");
            return;
        }
        String param = "{\"code\":\"" + code + "\"}";
        // 发送短信
        smsUtils.sendMessage(phone, prop.getSignName(), prop.getVerifyCodeTemplate(), param);
    }
}
